'use client';

import React, { useState } from 'react';
export interface Annotation {
    id: string;
    type: 'rectangle' | 'circle' | 'polygon' | 'line' | 'arrow' | 'text';
    coordinates: number[];
    properties: {
        color: string;
        strokeWidth: number;
        fillOpacity: number;
        label?: string;
        measurements?: {
            length?: number;
            area?: number;
            angle?: number;
        };
    };
    metadata: {
        createdAt: Date;
        createdBy: string;
        modifiedAt?: Date;
        modifiedBy?: string;
    };
}

interface ImageAnnotationsProps {
    annotations: Annotation[];
    selectedAnnotation: string | null;
    onUpdateAnnotation?: (id: string, updates: Partial<Annotation>) => void;
    onDeleteAnnotation?: (id: string) => void;
    onSelectAnnotation?: (id: string | null) => void;
    className?: string;
}

export const ImageAnnotations: React.FC<ImageAnnotationsProps> = ({
    annotations,
    selectedAnnotation,
    onUpdateAnnotation,
    onDeleteAnnotation,
    onSelectAnnotation,
    className = '',
}) => {
    const [isCollapsed, setIsCollapsed] = useState(false);
    const [editingAnnotation, setEditingAnnotation] = useState<string | null>(null);
    const [editLabel, setEditLabel] = useState('');

    const formatCoordinates = (coordinates: number[], type: string): string => {
        switch (type) {
            case 'rectangle':
                return `(${Math.round(coordinates[0])}, ${Math.round(coordinates[1])}) - (${Math.round(coordinates[2])}, ${Math.round(coordinates[3])})`;
            case 'circle':
                return `Center: (${Math.round(coordinates[0])}, ${Math.round(coordinates[1])}) R: ${Math.round(coordinates[2])}`;
            case 'line':
                return `(${Math.round(coordinates[0])}, ${Math.round(coordinates[1])}) - (${Math.round(coordinates[2])}, ${Math.round(coordinates[3])})`;
            case 'polygon':
                const points = [];
                for (let i = 0; i < coordinates.length; i += 2) {
                    points.push(`(${Math.round(coordinates[i])}, ${Math.round(coordinates[i + 1])})`);
                }
                return points.join(', ');
            default:
                return coordinates.map(c => Math.round(c)).join(', ');
        }
    };

    const getAnnotationIcon = (type: string): string => {
        switch (type) {
            case 'rectangle': return '⬜';
            case 'circle': return '⭕';
            case 'polygon': return '🔷';
            case 'line': return '📏';
            case 'arrow': return '➡️';
            case 'text': return '📝';
            default: return '📍';
        }
    };

    const handleStartEdit = (annotation: Annotation) => {
        setEditingAnnotation(annotation.id);
        setEditLabel(annotation.properties.label || '');
    };

    const handleSaveEdit = (annotationId: string) => {
        if (onUpdateAnnotation) {
            const annotation = annotations.find(a => a.id === annotationId);
            if (annotation) {
                onUpdateAnnotation(annotationId, {
                    properties: {
                        ...annotation.properties,
                        label: editLabel,
                    },
                });
            }
        }
        setEditingAnnotation(null);
        setEditLabel('');
    };

    const handleCancelEdit = () => {
        setEditingAnnotation(null);
        setEditLabel('');
    };

    const handleColorChange = (annotationId: string, color: string) => {
        if (onUpdateAnnotation) {
            const annotation = annotations.find(a => a.id === annotationId);
            if (annotation) {
                onUpdateAnnotation(annotationId, {
                    properties: {
                        ...annotation.properties,
                        color,
                    },
                });
            }
        }
    };

    const handleStrokeWidthChange = (annotationId: string, strokeWidth: number) => {
        if (onUpdateAnnotation) {
            const annotation = annotations.find(a => a.id === annotationId);
            if (annotation) {
                onUpdateAnnotation(annotationId, {
                    properties: {
                        ...annotation.properties,
                        strokeWidth,
                    },
                });
            }
        }
    };

    const calculateMeasurements = (annotation: Annotation): string | null => {
        if (!annotation.properties.measurements) return null;

        const { length, area, angle } = annotation.properties.measurements;
        const parts = [];

        if (length !== undefined) {
            parts.push(`Length: ${length.toFixed(2)} mm`);
        }
        if (area !== undefined) {
            parts.push(`Area: ${area.toFixed(2)} mm²`);
        }
        if (angle !== undefined) {
            parts.push(`Angle: ${angle.toFixed(1)}°`);
        }

        return parts.length > 0 ? parts.join(', ') : null;
    };

    return (
        <div className={`bg-white/90 backdrop-blur-sm rounded-lg shadow-lg ${className}`}>
            {/* Header */}
            <div className="flex items-center justify-between p-3 border-b">
                <h3 className="text-sm font-medium text-gray-900">
                    Annotations ({annotations.length})
                </h3>
                <button
                    onClick={() => setIsCollapsed(!isCollapsed)}
                    className="p-1 hover:bg-gray-100 rounded"
                >
                    <svg
                        className={`w-4 h-4 transition-transform ${isCollapsed ? 'rotate-180' : ''}`}
                        fill="none"
                        stroke="currentColor"
                        viewBox="0 0 24 24"
                    >
                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 9l-7 7-7-7" />
                    </svg>
                </button>
            </div>

            {/* Content */}
            {!isCollapsed && (
                <div className="max-h-96 overflow-y-auto">
                    {annotations.length === 0 ? (
                        <div className="p-4 text-center text-gray-500 text-sm">
                            No annotations yet. Use the drawing tools to add annotations.
                        </div>
                    ) : (
                        <div className="p-2 space-y-2">
                            {annotations.map((annotation) => (
                                <div
                                    key={annotation.id}
                                    className={`p-3 rounded-lg border cursor-pointer transition-colors ${selectedAnnotation === annotation.id
                                        ? 'border-blue-300 bg-blue-50'
                                        : 'border-gray-200 hover:border-gray-300 hover:bg-gray-50'
                                        }`}
                                    onClick={() => onSelectAnnotation?.(annotation.id)}
                                >
                                    {/* Annotation Header */}
                                    <div className="flex items-center justify-between mb-2">
                                        <div className="flex items-center gap-2">
                                            <span className="text-lg">{getAnnotationIcon(annotation.type)}</span>
                                            <div>
                                                <div className="text-sm font-medium capitalize">
                                                    {annotation.type}
                                                </div>
                                                <div className="text-xs text-gray-500">
                                                    {new Date(annotation.metadata.createdAt).toLocaleString()}
                                                </div>
                                            </div>
                                        </div>
                                        <div className="flex items-center gap-1">
                                            <button
                                                onClick={(e) => {
                                                    e.stopPropagation();
                                                    handleStartEdit(annotation);
                                                }}
                                                className="p-1 hover:bg-gray-200 rounded"
                                                title="Edit"
                                            >
                                                <svg className="w-3 h-3" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z" />
                                                </svg>
                                            </button>
                                            <button
                                                onClick={(e) => {
                                                    e.stopPropagation();
                                                    onDeleteAnnotation?.(annotation.id);
                                                }}
                                                className="p-1 hover:bg-red-100 text-red-600 rounded"
                                                title="Delete"
                                            >
                                                <svg className="w-3 h-3" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16" />
                                                </svg>
                                            </button>
                                        </div>
                                    </div>

                                    {/* Label */}
                                    <div className="mb-2">
                                        {editingAnnotation === annotation.id ? (
                                            <div className="flex gap-2">
                                                <input
                                                    type="text"
                                                    value={editLabel}
                                                    onChange={(e) => setEditLabel(e.target.value)}
                                                    className="flex-1 px-2 py-1 text-sm border rounded"
                                                    placeholder="Enter label..."
                                                    autoFocus
                                                />
                                                <button
                                                    onClick={() => handleSaveEdit(annotation.id)}
                                                    className="px-2 py-1 bg-blue-600 text-white text-xs rounded hover:bg-blue-700"
                                                >
                                                    Save
                                                </button>
                                                <button
                                                    onClick={handleCancelEdit}
                                                    className="px-2 py-1 bg-gray-300 text-gray-700 text-xs rounded hover:bg-gray-400"
                                                >
                                                    Cancel
                                                </button>
                                            </div>
                                        ) : (
                                            <div className="text-sm">
                                                <span className="font-medium">Label: </span>
                                                <span className="text-gray-600">
                                                    {annotation.properties.label || 'No label'}
                                                </span>
                                            </div>
                                        )}
                                    </div>

                                    {/* Coordinates */}
                                    <div className="text-xs text-gray-500 mb-2">
                                        <span className="font-medium">Position: </span>
                                        {formatCoordinates(annotation.coordinates, annotation.type)}
                                    </div>

                                    {/* Measurements */}
                                    {calculateMeasurements(annotation) && (
                                        <div className="text-xs text-blue-600 mb-2">
                                            <span className="font-medium">Measurements: </span>
                                            {calculateMeasurements(annotation)}
                                        </div>
                                    )}

                                    {/* Properties */}
                                    {selectedAnnotation === annotation.id && (
                                        <div className="mt-3 pt-3 border-t space-y-2">
                                            {/* Color Picker */}
                                            <div className="flex items-center gap-2">
                                                <label className="text-xs font-medium text-gray-600">Color:</label>
                                                <div className="flex gap-1">
                                                    {['#ff0000', '#00ff00', '#0000ff', '#ffff00', '#ff00ff', '#00ffff'].map((color) => (
                                                        <button
                                                            key={color}
                                                            onClick={() => handleColorChange(annotation.id, color)}
                                                            className={`w-6 h-6 rounded border-2 ${annotation.properties.color === color ? 'border-gray-800' : 'border-gray-300'
                                                                }`}
                                                            style={{ backgroundColor: color }}
                                                        />
                                                    ))}
                                                </div>
                                            </div>

                                            {/* Stroke Width */}
                                            <div className="flex items-center gap-2">
                                                <label className="text-xs font-medium text-gray-600">Stroke:</label>
                                                <input
                                                    type="range"
                                                    min="1"
                                                    max="10"
                                                    value={annotation.properties.strokeWidth}
                                                    onChange={(e) => handleStrokeWidthChange(annotation.id, Number(e.target.value))}
                                                    className="flex-1 h-1"
                                                />
                                                <span className="text-xs text-gray-500 w-6">
                                                    {annotation.properties.strokeWidth}
                                                </span>
                                            </div>

                                            {/* Created By */}
                                            <div className="text-xs text-gray-500">
                                                <span className="font-medium">Created by: </span>
                                                {annotation.metadata.createdBy}
                                                {annotation.metadata.modifiedAt && (
                                                    <>
                                                        <br />
                                                        <span className="font-medium">Modified: </span>
                                                        {new Date(annotation.metadata.modifiedAt).toLocaleString()}
                                                    </>
                                                )}
                                            </div>
                                        </div>
                                    )}
                                </div>
                            ))}
                        </div>
                    )}
                </div>
            )}
        </div>
    );
};

export default ImageAnnotations;